/**
 * by wit on 2024-03-06
 * 路由拦截，通常也是登录拦截
 * 可以设置路由白名单，或者黑名单，看业务需要选哪一个
 * 我这里应为大部分都可以随便进入，所以使用黑名单
 */
import { PageWhiteListEnum } from "@/enums/appEnums";
import { BACK_URL } from "@/enums/cacheEnums";
import { useUserStore } from "@/store/modules/user";
import { getNoNeedLoginPages } from "@/utils";
import { getToken } from "@/utils/auth";
import cache from "@/utils/cache";
import wechatOa from "@/utils/wechat";

// TODO Check
const whiteListSet = new Set();
let isFirstUrl = true;
Object.values(PageWhiteListEnum).forEach((item) => {
  whiteListSet.add(item);
});
// 白名单登录拦截器 - （适用于少部分页面不需要登录，大部分页面需要登录）
export const urlInterceptors = () => {
  // 获取地址栏当前url
  const currentUrl = window.location.href;
  const url = new URL(currentUrl);
  let path = url.pathname;
  if (path === "/") {
    path = "/pages/home/index";
  }
  console.log("地址框路由拦截器", path);

  //收集微信公众号的授权code，并清楚路径上微信带的参数
  const code = url.searchParams.get("code");
  const state = url.searchParams.get("state");
  const scene = url.searchParams.get("scene");
  // console.log("用户输入的url", "code", code, "state", state, "scene", scene);
  // 如果有code并且有state，则保存到微信授权信息中
  if (code && scene === "login") {
    wechatOa.setAuthData({
      code,
      scene,
    });
  }

  let noNeedLoginPages: string[] = [];
  // 获取所有不要登录权限的页面
  noNeedLoginPages = getNoNeedLoginPages();
  // console.log("noNeedLoginPages", noNeedLoginPages);
  const isNoNeedLogin = noNeedLoginPages.includes(path);

  if (isNoNeedLogin) {
    return true;
  }
  const { token } = useUserStore();
  if (token) {
    return true;
  }

  if (isFirstUrl) {
    cache.set(BACK_URL, path+'?'+url.search);
    isFirstUrl = false;
  }
  if (whiteListSet.has(path)) {
    return;
  }
  // 携带跳转路径构造重定向路径
  const redirectRoute = `${
    PageWhiteListEnum.LOGIN
  }?redirect=${encodeURIComponent(path)}`;
  uni.navigateTo({ url: redirectRoute });
  // debugger
};

//收集微信公众号的授权code，并清楚路径上微信带的参数

// uni.navigateTo reLaunch redirectTo switchTab 的拦截器
const navigateToInterceptor = {
  // 注意，这里的url是 '/' 开头的，如 '/pages/index/index'，跟 'pages.json' 里面的 path 不同

  invoke: ({ url }: { url: string }) => {
    const path = url.split("?")[0];
    console.log("navigate路由拦截器", path); // /pages/route-interceptor/index?name=feige&age=30
    console.log("path", path);
    let noNeedLoginPages: string[] = [];
    // 获取所有不要登录权限的页面
    noNeedLoginPages = getNoNeedLoginPages();
    // console.log("noNeedLoginPages", noNeedLoginPages);
    const isNoNeedLogin = noNeedLoginPages.includes(path);
    if (isNoNeedLogin) {
      return true;
    }
    const { token } = useUserStore();
    if (token) {
      return true;
    }
    const redirectRoute = `${
      PageWhiteListEnum.LOGIN
    }?redirect=${encodeURIComponent(url)}`;
    uni.navigateTo({ url: redirectRoute });
    return false;
  },
};

export const routeInterceptor = {
  install() {
    console.log("路由拦截器安装");
    uni.addInterceptor("navigateTo", navigateToInterceptor);
    uni.addInterceptor("reLaunch", navigateToInterceptor);
    uni.addInterceptor("redirectTo", navigateToInterceptor);
    uni.addInterceptor("switchTab", navigateToInterceptor);
  },
};
